﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using KPIS.GERP.GBMS.APP;
using KPIS.GERP.GBMS.IBLL;
using KPIS.GERP.GBMS.BLL;
using System.Configuration;
using System.Data;
using Telerik.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Globalization;
using KPIS.GERP.GBMS.MODEL;
using System.Collections;


namespace KPIS.GERP.GBMS.APP_UI.Form
{
    public partial class BGM_Approve_Header : System.Web.UI.Page
    {
        private ComboBLL comboBLL = new ComboBLL();

        private IProjectHeader pjHeaderBLL;


        protected void Page_Load(object sender, EventArgs e)
        {
            string type = Request.QueryString["type"].ToString();
            if (type.Length > 0)
            {
                hdfHeaderType.Value = type;
                pjHeaderBLL = Project_Factory.GetProjectHeaderFactory(type);
            }
            InitializedPage();

            this.PreRender += new EventHandler(Pre_render);
        }

        protected void Pre_render(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
               // ddlYear.indexChange += new RadComboBoxSelectedIndexChangedEventHandler(OnSelectedIndexChanged);
                LoadYear();
                LoadGrid();
            }
            
        }
        private void LoadYear()
        {
            int CurrYear = SystemInfo._CurrentYearReq;
            ddlYear.Items.Clear();

            for (int i = CurrYear + 5; i >= CurrYear - 5; i--)
            {
                ddlYear.Items.Add(new RadComboBoxItem(i.ToString(), i.ToString()));
            }
            ddlYear.SelectedValue = CurrYear.ToString();
        }
        private void InitializedPage()
        {
            string type = Request.QueryString["type"].ToString();

            if (type == "ap")
            {

                //lstReq.Visible = true;
                //lstApp.Visible = true;
                lbTable.Text = "ตารางแสดงข้อมูลประชุมพิจารณางบประมาณ";
                lbStep1.Text = "ขั้นตอนที่ 1 : กรอกหัวเรื่องการประชุมเพื่อพิจารณางบประมาณ";
                lbStep2.Text = "ขั้นตอนที่ 2 : เลือกงาน/โครงการจากคำของบประมาณที่ต้องการนำเข้าประชุม";
                lbFrom.Text = "|----------------- งาน/โครงการจากคำของบประมาณ -----------------|";
                lbTo.Text = "|----------------- งาน/โครงการที่ต้องการนำเข้าประชุม -----------------|";

                Grid.MasterTableView.CommandItemDisplay = GridCommandItemDisplay.None;
                Grid.Columns[0].Visible = false;
                Grid.Columns[1].Visible = false;

                Grid.Columns[2].HeaderText = "หัวข้อการประชุมพิจารณางบประมาณ";
                Grid.Columns[3].HeaderText = "เสนอของบประมาณ(บาท)";
                Grid.Columns[4].HeaderText = "ผ่านการพิจารณา(บาท)";

                Grid.Columns[2].HeaderStyle.Width = Unit.Percentage(40);
                Grid.Columns[3].HeaderStyle.Width = Unit.Percentage(20);
                Grid.Columns[4].HeaderStyle.Width = Unit.Percentage(20);
            }
            else if(type == "md")
            {
                lbTable.Text = "ตารางแสดงข้อมูลประชุมพิจารณางบประมาณ";
                lbStep1.Text = "ขั้นตอนที่ 1 : กรอกหัวเรื่องการประชุมเพื่อพิจารณางบประมาณ";
                lbStep2.Text = "ขั้นตอนที่ 2 : เลือกงาน/โครงการจากคำของบประมาณที่ต้องการนำเข้าประชุม";
                lbFrom.Text = "|--------------- งาน/โครงการจากคำของบประมาณ ---------------|";
                lbTo.Text = "|-------------- งาน/โครงการที่ต้องการนำเข้าประชุม --------------|";

                Grid.Columns[2].HeaderText = "หัวข้อการประชุมพิจารณางบประมาณ";
                Grid.Columns[3].HeaderText = "เสนอของบประมาณ(บาท)";
                Grid.Columns[4].HeaderText = "ผ่านการพิจารณา(บาท)";
                //Grid.Columns[4].Visible = false; //#romdorn

                Grid.Columns[2].HeaderStyle.Width = Unit.Percentage(40);
                Grid.Columns[3].HeaderStyle.Width = Unit.Percentage(20);
                Grid.Columns[4].HeaderStyle.Width = Unit.Percentage(20);
            }
            else if (type == "rc")
            {
                lbTable.Text = "ตารางแสดงข้อมูลประชุมจัดสรรงบประมาณตามพระราชบัญญัติงบประมาณ";
                lbStep1.Text = "ขั้นตอนที่ 1 : กรอกหัวเรื่องการประชุมเพื่อพิจารณาจัดสรรงบประมาณประจำปี";
                lbStep2.Text = "ขั้นตอนที่ 2 : เลือกเอกสารคำของบประมาณที่ต้องการจัดสรร";
                lbFrom.Text = "|--------------- เอกสารรวมรวบคำของบประมาณ ---------------|";
                lbTo.Text = "|-------- เอกสารรวมรวบคำของบประมาณที่ต้องการจัดสรร --------|";

                Grid.Columns[2].HeaderText = "หัวข้อการประชุมจัดสรรงบประมาณตาม พ.ร.บ.";
                Grid.Columns[3].HeaderText = "เสนอของบประมาณ(บาท)";
                Grid.Columns[4].HeaderText = "ได้รับจัดสรรงบประมาณ(บาท)";
   
                Grid.Columns[2].HeaderStyle.Width = Unit.Percentage(40);
                Grid.Columns[3].HeaderStyle.Width = Unit.Percentage(20);
                Grid.Columns[4].HeaderStyle.Width = Unit.Percentage(20);

                lbReqStratList.Visible = false;
                lbReqJobSite.Visible = false;
                ddlStrategy.Visible = false;
                ddlJobSite.Visible = false;

                lbAppStratList.Visible = false;
                lbAppJobSite.Visible = false;
                ddlStrategy1.Visible = false;
                ddlJobSite1.Visible = false;
            }
        }

        private void LoadGrid()
        {
            //RadComboBox cmbYear = (RadComboBox)ddlYear.FindControl("year");

            DataTable dt = pjHeaderBLL.GetDataProjectHeaderByYear(Convert.ToInt16(ddlYear.SelectedValue.ToString()));
            Grid.DataSource = dt;
            Grid.DataBind();

        }

        private void LoadStrategyCombo()
        {
            //RadComboBox cmbYear = (RadComboBox)ddlYear.FindControl("year");
            DataTable dt = comboBLL.ListStrategy(ddlYear.SelectedValue);

            ddlStrategy.DataSource = dt;
            ddlStrategy.DataBind();

            ddlStrategy.Items.Insert(0, new RadComboBoxItem("----- กิจกรรมย่อยทั้งหมด -----", ""));

            ddlStrategy1.DataSource = dt;
            ddlStrategy1.DataBind();

            ddlStrategy1.Items.Insert(0, new RadComboBoxItem("----- กิจกรรมย่อยทั้งหมด -----", ""));
        }

        private void LoadJobSiteCombo()
        {
            DataTable dt = comboBLL.ListJobsite();
            ddlJobSite.DataSource = dt;
            ddlJobSite.DataBind();

            ddlJobSite.Items.Insert(0, new RadComboBoxItem("----- หน่วยงานทั้งหมด -----", ""));

            ddlJobSite1.DataSource = dt;
            ddlJobSite1.DataBind();

            ddlJobSite1.Items.Insert(0, new RadComboBoxItem("----- น่วยงานทั้งหมด -----", ""));

        }

        
        private void LoadListBoxRequest(string bgm_prj_header_seq)
        {
            DataTable info = pjHeaderBLL.ListRequest(ddlYear.SelectedValue, ddlStrategy.SelectedValue, ddlJobSite.SelectedValue, bgm_prj_header_seq);
            lstReq.DataValueField = "Value";
            lstReq.DataTextField = "Text";
            lstReq.DataSource = info;
            lstReq.DataBind();
            checkItems();
        }

        private void LoadListBoxApproval(string seq)
        {
            DataTable info = pjHeaderBLL.ListApproval(seq);
            lstApp.DataValueField = "Value";
            lstApp.DataTextField = "Text";
            lstApp.DataSource = info;
            lstApp.DataBind();
        }

        
        private void LoadDataforEdit(int seq)
        {
            pnDetail.Visible = true;
            LoadStrategyCombo();
            LoadJobSiteCombo();
            lblHeader_seq.Text = seq.ToString();
            DataTable dt = pjHeaderBLL.GetDataProjectHeaderBySequence(lblHeader_seq.Text);
            DataRow dr = dt.Rows[0];

            //RadComboBox cmbYear = (RadComboBox)ddlYear.FindControl("year");
            ddlYear.SelectedValue = dr["bgm_year"].ToString();
            try
            {
                string mydate = dr["bgm_prj_header_date"].ToString();
                string[] str = mydate.Split('/');
                str[2] = (int.Parse(str[2].Substring(0, 4)) + 543).ToString();
                str[0] = str[0].Length > 1 ? str[0] : "0" + str[0];
                mydate = str[1] + "/" + str[0] + "/" + str[2];
                txtDate.Text = mydate;
            }
            catch
            { }
            txtName.Text = dr["bgm_prj_header_name"].ToString();
            txtDescr.Text = dr["bgm_prj_header_descr"].ToString();
            txtRemark.Text = dr["remark"].ToString();
            LoadListBoxApproval(lblHeader_seq.Text);
            LoadListBoxRequest(seq.ToString());
        }

        private void Clear()
        {
            //RadComboBox cmbYear = (RadComboBox)ddlYear.FindControl("year");
            //ddlYear.SelectedValue = SystemInfo._CurrentYearReq.ToString();
            txtDate.Text = "";
            txtName.Text = "";
            txtDescr.Text = "";
            txtRemark.Text = "";
            ddlStrategy.ClearSelection();
            ddlStrategy.Text = string.Empty;
            ddlJobSite.ClearSelection();
            ddlJobSite.Text = string.Empty;
            //LoadListBoxRequest("");

            //for (int i = lstApp.Items.Count - 1; i >= 0; i--)
            //{
            //    lstReq.Items.Add(new ListItem(lstApp.Items[i].Text, lstApp.Items[i].Value));
            //    lstApp.Items.Remove(lstApp.Items[i]);
            //}
        }

        protected void Grid_ItemCommand(object source, GridCommandEventArgs e)
        {
            if (e.CommandName == "Delete")
            {
                int nRowSelected = 0;
                foreach (GridDataItem data in Grid.MasterTableView.GetSelectedItems())
                {
                    pjHeaderBLL.DeleteProjectHeader(Convert.ToInt32(data.OwnerTableView.DataKeyValues[data.ItemIndex]["Sequence"]));
                    nRowSelected++;
                }
            }
            if (e.CommandName == "Approve")
            {
                int nRowSelected = 0;
                foreach (GridDataItem data in Grid.MasterTableView.GetSelectedItems())
                {
                    pjHeaderBLL.ApproveTransaction(data.OwnerTableView.DataKeyValues[data.ItemIndex]["Sequence"].ToString(), new SsMng().GetUss(SsMng.SsUserType.EmpSeq));
                    nRowSelected++;
                }
            }
            if (e.CommandName == RadGrid.EditCommandName)
            {
                int seq = Convert.ToInt32((e.Item as GridDataItem).OwnerTableView.DataKeyValues[e.Item.ItemIndex]["Sequence"]);
                LoadGrid();
                LoadDataforEdit(seq);
                btnSave.Visible = false;
                btnEdit.Visible = true;
            }
        }

        //protected void OnSelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        //{
        //    LoadStrategyCombo();
        //    LoadListBoxRequest("");
        //}
        protected void ddlYear_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            //LoadStrategyCombo();
            LoadGrid();
            pnDetail.Visible = false;
            Clear();
        }

        protected void ddlStrategy_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            LoadListBoxRequest(lblHeader_seq.Text);
        }

        protected void ddlJobSite_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            LoadListBoxRequest(lblHeader_seq.Text);
        }

        protected void RadAjaxManager1_AjaxRequest(object sender, AjaxRequestEventArgs e)
        {
            //if (e.Argument == "CloseWindow")
            //    return;

            //LoadListBoxRequest(e.Argument, lblHeader_seq.Text);
        }

        protected void btnAddNew_Click(object sender, EventArgs e)
        {
            Clear();
            lblHeader_seq.Text = "";
            pnDetail.Visible = true;
            LoadStrategyCombo();
            LoadJobSiteCombo();
            LoadListBoxRequest("");
            btnEdit.Visible = false;
            btnSave.Visible = true;

            LoadListBoxRequest("");
            lstApp.Items.Clear();
            //for (int i = lstApp.Items.Count - 1; i >= 0; i--)
            //{
            //    lstApp.Items.Remove(lstApp.Items[i]);
            //}
        }

        protected void checkItems()
        {
            for (int r = lstReq.Items.Count - 1; r >= 0; r--)
            {
                for (int a = lstApp.Items.Count - 1; a >= 0; a--)
                {
                    if (lstReq.Items[r].Text == lstApp.Items[a].Text)
                    {
                        lstReq.Items.Remove(lstReq.Items[r]);
                    }
                    continue;
                }
            }
        }

        protected void btnSelect_Cleck(object sender, EventArgs e)
        {
            for (int i = lstReq.Items.Count - 1; i >= 0; i--)
            {
                if (lstReq.Items[i].Selected)
                {
                    lstApp.Items.Add(new ListItem(lstReq.Items[i].Text, lstReq.Items[i].Value));
                    lstReq.Items.Remove(lstReq.Items[i]);
                }
            }
        }

        protected void btnSelectAll_Cleck(object sender, EventArgs e)
        {
            for (int i = lstReq.Items.Count - 1; i >= 0; i--)
            {
                lstApp.Items.Add(new ListItem(lstReq.Items[i].Text, lstReq.Items[i].Value));
                lstReq.Items.Remove(lstReq.Items[i]);
            }
        }

        protected void btnRemove_Cleck(object sender, EventArgs e)
        {
            for (int i = lstApp.Items.Count - 1; i >= 0; i--)
            {
                if (lstApp.Items[i].Selected)
                {
                    lstReq.Items.Add(new ListItem(lstApp.Items[i].Text, lstApp.Items[i].Value));
                    lstApp.Items.Remove(lstApp.Items[i]);
                }
            }
        }

        protected void btnRemoveAll_Cleck(object sender, EventArgs e)
        {
            for (int i = lstApp.Items.Count - 1; i >= 0; i--)
            {
                lstReq.Items.Add(new ListItem(lstApp.Items[i].Text, lstApp.Items[i].Value));
                lstApp.Items.Remove(lstApp.Items[i]);
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            pnDetail.Visible = false;
            Clear();
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            string myDate = "";// Utils.Date.ToEngFormatDate(txtDate.TextWithLiterals);
            myDate = myDate.Replace(" ", "");
            int header_seq = pjHeaderBLL.InsertProjectHeader(txtName.Text, txtDescr.Text, myDate.ToString(), "", ddlYear.SelectedValue, txtRemark.Text, null, new SsMng().GetUss(SsMng.SsUserType.EmpSeq));   // บันทึก header
            DataTable tmpDT = new DataTable();
            DataTable tmpDT_FN = new DataTable();
            string bgm_app_seq = "";
            string strat_list_seq = "";
            for (int i = lstApp.Items.Count - 1; i >= 0; i--)   //loop bgm_reg_seq
            {
                pjHeaderBLL.InsertProject(header_seq.ToString(), lstApp.Items[i].Value, new SsMng().GetUss(SsMng.SsUserType.EmpSeq));

                //##new
                DataTable dt = pjHeaderBLL.GetDataProjectSourceBySequence(header_seq.ToString(), lstApp.Items[i].Value);
                bgm_app_seq = dt.Rows[0]["bgm_app_seq"].ToString();
                strat_list_seq = dt.Rows[0]["bgm_strat_list_seq"].ToString();

                if (i == lstApp.Items.Count - 1)
                {
                    tmpDT = dt;
                    tmpDT_FN = dt;
                }
                foreach (DataRow dr in dt.Rows)   // loop แหล่งเงิน
                {
                    // โครงการ
                    decimal totalAmountDR = dr["total_amount"].ToString().Trim().Length > 0 ? Convert.ToDecimal(dr["total_amount"]) : 0;
                    pjHeaderBLL.InsertApprovalSource(bgm_app_seq, dr["bgm_source_seq"].ToString(), totalAmountDR, totalAmountDR, new SsMng().GetUss(SsMng.SsUserType.EmpSeq));

                    //dr["bgm_strat_list_seq"] =  dt.Rows[0]["bgm_strat_list_seq"].ToString();
                    // กิจกรรม
                    foreach (DataRow tmpDR in tmpDT.Rows)
                    {
                        decimal totalAmountTmpDR = tmpDR["total_amount"].ToString().Trim().Length > 0 ? Convert.ToDecimal(tmpDR["total_amount"]) : 0;
                        if (tmpDR["bgm_source_seq"].ToString() == dr["bgm_source_seq"].ToString())
                        {
                            if (i != lstApp.Items.Count - 1)
                                tmpDR["total_amount"] = totalAmountTmpDR + totalAmountDR;
                        }
                    }
                    tmpDT_FN.Rows.Add(dr);
                }
                //tmpDT.AcceptChanges();
            }
            foreach (DataRow dr in tmpDT.Rows)
            {
                decimal totalAmount = dr["total_amount"].ToString().Length > 0 ? Convert.ToDecimal(dr["total_amount"]) : 0;
                pjHeaderBLL.InsertApprovalStrategy(header_seq.ToString(), strat_list_seq.ToString(), dr["bgm_source_seq"].ToString(), totalAmount, totalAmount, new SsMng().GetUss(SsMng.SsUserType.EmpSeq));
            }
            //##end new

            pjHeaderBLL.InsertProjectControl(header_seq.ToString(), new SsMng().GetUss(SsMng.SsUserType.EmpSeq));
            RadAjaxManager1.Alert("บันทึกเรียบร้อยแล้ว");
            Clear();
            LoadGrid();
            pnDetail.Visible = false;
        }

        protected void btnEdit_Click(object sender, EventArgs e)
        {
            string myDate = "";// Utils.Date.ToEngFormatDate(txtDate.TextWithLiterals);
            myDate = myDate.Replace(" ", "");
            //RadComboBox cmbYear = (RadComboBox)ddlYear.FindControl("year");
            pjHeaderBLL.UpdateProjectHeader(lblHeader_seq.Text, ddlYear.SelectedValue, myDate, txtName.Text, txtDescr.Text, txtRemark.Text, new SsMng().GetUss(SsMng.SsUserType.EmpSeq));

            DataTable dt = pjHeaderBLL.GetDataProjectBySequence(lblHeader_seq.Text);
            int sta = 0;
            for (int i = 0; i < lstApp.Items.Count; i++) // loop listbox
            {
                DataRow[] dr;
                dr = dt.Select("bgm_prj_seq=" + lstApp.Items[i].Value);
                if (dr.Length != 0)
                {
                    sta = 0;
                }
                else
                {
                    pjHeaderBLL.InsertProject(lblHeader_seq.Text, lstApp.Items[i].Value, new SsMng().GetUss(SsMng.SsUserType.EmpSeq));
                    sta = 1;
                }
            }
            if (sta != 0)
            {
                pjHeaderBLL.InsertProjectControl(lblHeader_seq.Text, new SsMng().GetUss(SsMng.SsUserType.EmpSeq));
            }
            foreach (DataRow dr2 in dt.Rows) // loop dt
            {
                int faq = 0;
                for (int i = 0; i < lstApp.Items.Count; i++)
                {
                    if (dr2["bgm_prj_seq"].ToString() == lstApp.Items[i].Value)
                        faq = 1;
                }
                if (faq != 1)
                    pjHeaderBLL.DeleteProject(Convert.ToInt32(dr2["bgm_prj_seq"]));
            }
            RadAjaxManager1.Alert("บันทึกเรียบร้อยแล้ว");
            LoadGrid();
            pnDetail.Visible = false;
            Clear();
        }
    }
}
